package CustomerGUIs;

/**
 *
 * @author bagi
 */

import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import Model.Customer;
import Model.InternalDBManager;
import javax.persistence.NoResultException;
import javax.swing.ImageIcon;
import Supermarket.AppMessages;
import Supermarket.LoginUser;

public class ChangePasswordForm extends javax.swing.JDialog {
     
   private static EntityManager em;
   private LoginUser loginUser;
   private Customer customer; 
   
      /**
     * Creates new form ChangePasswordForm
     */
   public ChangePasswordForm() {
        try {   
           em = InternalDBManager.getEm();
        } catch (Exception e) {
            System.out.println("ERROR (++):¨"+e.getMessage());
        }
        initComponents();
        this.setIconImage(new
                ImageIcon(getClass().getResource("..\\Images\\cart.png")).getImage());
        setAlwaysOnTop(true);
    } 
      
    /**
     * Creates new form ChangePasswordForm
     * 
     * @param loginUser o χρήστης που έχει κάνει login
     */
   public ChangePasswordForm(LoginUser loginUser) {
       this.loginUser = loginUser;
        try {   
           em = InternalDBManager.getEm();
        } catch (Exception e) {
            System.out.println("ERROR (++):¨"+e.getMessage());
        }
        initComponents();
        this.setAlwaysOnTop(true);
        this.UserNameField.setText(loginUser.getUserName());
        this.UserNameField.setEnabled(false);
        this.setIconImage(new
                ImageIcon(getClass().getResource("..\\Images\\cart.png")).getImage()); 
        setAlwaysOnTop(true);
    }    
      
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        ConfirmPasswordField = new javax.swing.JPasswordField();
        OldPasswordField = new javax.swing.JPasswordField();
        NewPasswordField = new javax.swing.JPasswordField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        UserNameField = new javax.swing.JTextField();
        RegisterButton = new javax.swing.JButton();
        CancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Αλλαγή κωδικού πρόσβασης");
        setIconImage(null);

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        ConfirmPasswordField.setMaximumSize(new java.awt.Dimension(22, 22));
        ConfirmPasswordField.setMinimumSize(new java.awt.Dimension(6, 22));
        ConfirmPasswordField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                ConfirmPasswordFieldFocusGained(evt);
            }
        });

        OldPasswordField.setMaximumSize(new java.awt.Dimension(22, 22));
        OldPasswordField.setMinimumSize(new java.awt.Dimension(6, 22));
        OldPasswordField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                OldPasswordFieldFocusGained(evt);
            }
        });

        NewPasswordField.setMaximumSize(new java.awt.Dimension(22, 22));
        NewPasswordField.setMinimumSize(new java.awt.Dimension(6, 22));
        NewPasswordField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                NewPasswordFieldFocusGained(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("old password:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("new password:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel5.setText("confirm password:");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setText("user name:");

        UserNameField.setMaximumSize(new java.awt.Dimension(22, 22));
        UserNameField.setMinimumSize(new java.awt.Dimension(6, 22));

        RegisterButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/save_16.png"))); // NOI18N
        RegisterButton.setText("Καταχώρηση");
        RegisterButton.setName(""); // NOI18N
        RegisterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RegisterButtonActionPerformed(evt);
            }
        });

        CancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/cancel_16.png"))); // NOI18N
        CancelButton.setText("Ακύρωση");
        CancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(OldPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(NewPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(UserNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ConfirmPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(RegisterButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CancelButton)
                .addGap(37, 37, 37))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(UserNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(OldPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(NewPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ConfirmPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CancelButton)
                    .addComponent(RegisterButton))
                .addGap(19, 19, 19))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void NewPasswordFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_NewPasswordFieldFocusGained
        // TODO add your handling code here:
        NewPasswordField.selectAll();
    }//GEN-LAST:event_NewPasswordFieldFocusGained

    private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegisterButtonActionPerformed

//***πρέπει με κάποιον τρόπο να φέρω το χρήστη στη μέθοδο***//    
        //UserNameField.setText(LoginForm.userName);
        String message = null;    //Μεταβλητή εμφάνισης μηνυμάτων
        String userName = UserNameField.getText();
        String password = String.copyValueOf(OldPasswordField.getPassword());
        String newPassword = String.copyValueOf(NewPasswordField.getPassword());
        String confirmPassword = String.copyValueOf(ConfirmPasswordField.getPassword());
        
        //Έλεγχος1: αν ο χρήστης είναι ανύπαρκτoς
        if (!(IsCustomerInDB(userName,password)))
            message = "Τα στοιχεία εισόδου είναι λανθασμένα!";
        else {//Έλεγχος2: ο νέος κωδικός ίδιος με τον παλιό
            if (password.equals(newPassword)){
                message = "Νέος κωδικός ίδιος με τον παλιό!";
            } else { //Έλεγχος3: μη επιβεβαίωση νέου κωδικού
                if (!(confirmPassword.equals(newPassword)))
                    message = "Οι κωδικοί δεν ταιριάζουν!";
            }
        }
    
        //Σε περίπτωση ανεπιτυχούς αλλαγής, εμφανίζεται αντίστοιχο μήνυμα λάθους
        if (message!=null) 
            JOptionPane.showMessageDialog(this, message,"ΠΡΟΣΟΧΗ",JOptionPane.WARNING_MESSAGE);
        else { //διαφορετικά ενημερώνεται η βάση με το νέο password του πελάτη
            customer.setPassword(newPassword);
            if (!em.getTransaction().isActive()) {
                em.getTransaction().begin();
            }
            em.persist(customer);
            em.getTransaction().commit();
            //Εμφανίζει μήνυμα επιτυχίας 
            AppMessages.SuccessChangePswMessage(this);
            this.dispose();
        }
    }//GEN-LAST:event_RegisterButtonActionPerformed

    private void CancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelButtonActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_CancelButtonActionPerformed

    private void OldPasswordFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_OldPasswordFieldFocusGained
        // TODO add your handling code here:
        OldPasswordField.selectAll();
    }//GEN-LAST:event_OldPasswordFieldFocusGained

    private void ConfirmPasswordFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ConfirmPasswordFieldFocusGained
        // TODO add your handling code here:
        ConfirmPasswordField.selectAll();
    }//GEN-LAST:event_ConfirmPasswordFieldFocusGained
    
    //Ελέγχει αν ο πελάτης υπάρχει στη ΒΔ
    public boolean IsCustomerInDB(String u, String p){
        boolean success = false;
        try{
            if (!em.getTransaction().isActive()){
                    em.getTransaction().begin();
            }  
            //ψάχνει τον χρήστη στη ΒΔ
            this.customer = (Customer) (Customer) em.createNamedQuery("Customer.findByPointsCardNumber")
                .setParameter("pointsCardNumber",u).getSingleResult();
            //αν βρεθεί ελέχεται το password
            if (p.equals(customer.getPassword())){
                success = true;
            }
        }catch(NoResultException e){
            //αν δε βρεθεί επιστρέφει false
            success = false;
        }
        return success;
    }       
        
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ChangePasswordForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ChangePasswordForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ChangePasswordForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ChangePasswordForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
                new ChangePasswordForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton CancelButton;
    private javax.swing.JPasswordField ConfirmPasswordField;
    private javax.swing.JPasswordField NewPasswordField;
    private javax.swing.JPasswordField OldPasswordField;
    private javax.swing.JButton RegisterButton;
    private javax.swing.JTextField UserNameField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables
}
